//
//  JTDesignableTextField.swift
//  JT Center
//
//  Created by Kiyo on 2021/3/19.
//  Copyright © 2021 J&T Express. All rights reserved.
//

import UIKit

@IBDesignable
public class JTTextField: UITextField {
    
    /// 左侧间距
    @IBInspectable
    public var leftPending: CGFloat = 10 {
        didSet {
            updateleftView()
        }
    }
    
    /// 左侧图片
    @IBInspectable
    public var leftImage: UIImage? {
        didSet {
            updateleftView()
        }
    }
    
    /// 清除已输入的按钮图片
    @IBInspectable
    public var clearImage: UIImage? {
        didSet {
            updateClearButton()
        }
    }
    
    /// 占位文字颜色
    @IBInspectable
    public var placeholderColor: UIColor? {
        didSet {
            updatePlaceholder()
        }
    }
    
    /// 清除已输入的按钮偏移量
    @IBInspectable
    public var clearButtonOffset: UIOffset = .zero
    
    /// 文字内容间距
    @IBInspectable
    public var textInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    
    
    
    public override func leftViewRect(forBounds bounds: CGRect) -> CGRect {
        var textRect = super.leftViewRect(forBounds: bounds)
        textRect.origin.x += leftPending
        return textRect
    }
    
    public override func textRect(forBounds bounds: CGRect) -> CGRect {
        let temp_bounds = bounds.inset(by: textInsets)
        return super.textRect(forBounds: temp_bounds)
    }
    
    public override func editingRect(forBounds bounds: CGRect) -> CGRect {
        let temp_bounds = bounds.inset(by: textInsets)
        return super.editingRect(forBounds: temp_bounds)
    }
    
    public override func clearButtonRect(forBounds bounds: CGRect) -> CGRect {
        let result = bounds.offsetBy(dx: clearButtonOffset.horizontal, dy: clearButtonOffset.vertical)
        return super.clearButtonRect(forBounds: result)
    }
    
    
    private func updateClearButton() {
        
        guard let clearBtn = value(forKey: "_clearButton") as? UIButton, let clearImg = clearImage else { return }
        clearBtn.setImage(clearImg, for: .normal)
    }
    
    private func updateleftView() {
        
        guard let leftImg = leftImage else {
            leftViewMode = UITextField.ViewMode.never
            leftView = nil
            return
        }
        
        leftViewMode = UITextField.ViewMode.always
        let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: leftImg.size.width, height: leftImg.size.height))
        imageView.contentMode = .scaleAspectFit
        imageView.image = leftImg
        leftView = imageView
    }
    
    
    private func updatePlaceholder() {
        
        guard let placeStr = placeholder, let placeColor = placeholderColor else { return }
        attributedPlaceholder = NSAttributedString(string: placeStr, attributes:[.foregroundColor: placeColor])
    }
}
